<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import DictTypeSee from './components/DictTypeSee.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  sysDictTypeListApi,
  sysDictTypeAddApi,
  sysDictTypeEditApi,
  sysDictTypeDelApi
} from '@/api/dict'
import { dictType } from '@/api/dict/types'
import { useTable } from '@/hooks/web/useTableTest'

const { register, tableObject, methods } = useTable<
  {
    count: number
    data: dictType[]
  },
  dictType
>({
  getListApi: sysDictTypeListApi,
  response: {
    count: 'count',
    data: 'data'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'dict_type_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    form: {
      show: false
    }
  },
  {
    field: 'name',
    label: '类型名称',
    search: {
      show: true
    }
  },
  {
    field: 'code',
    label: '类型代码',
    search: {
      show: true
    }
  },
  {
    field: 'note',
    label: '备注',
    form: {
      colProps: {
        span: 24
      },
      component: 'Input',
      componentProps: {
        type: 'textarea'
      },
      show: true
    }
  },
  {
    field: 'creation_time',
    label: '创建时间',
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = (type: string, row: dictType) => {
  actionType.value = type
  switch (type) {
    case 'add':
      dialogTitle.value = t('新增')
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'edit':
      dialogTitle.value = t('编辑')
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = t('详情')
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.dict_type_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      break
  }
}

const apiDel = async (dict_type_id) => {
  let delRes = await sysDictTypeDelApi({ dict_type_id: dict_type_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  if (actionType.value == 'add') {
    const write = unref(editRef)
    await write?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await write?.getFormData()) as dictType
        const res = await sysDictTypeAddApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  } else {
    const write = unref(editRef)
    await write?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await write?.getFormData()) as dictType
        const res = await sysDictTypeEditApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add', {})">{{ t('exampleDemo.add') }}</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action('edit', row)">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action('see', row)">
          {{ t('exampleDemo.detail') }}
        </ElButton>
        <ElButton type="danger" @click="action('del', row)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <DictTypeSee
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
